const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../utils/user.js');

//获取应用实例
const app = getApp();

Page({
  data: {
    goodsCount: 0,
    number: 0,
    money: 0,
    banner: [],
    channel: [],
    hotGoods: [],
    groupons: [],
    newGoods: [],
    noStockGoods: [],
    coupon: [],
    indicatorDots: false,
    window: false,
    colseCoupon: false
  },

  onShareAppMessage: function () {
    let userInfo = wx.getStorageSync('userInfo');
    let shareUserId = 1;
    if (userInfo) {
      shareUserId = userInfo.userId;
    }
    console.log('/pages/index/index?shareUserId=' + shareUserId);
    return {
      title: '金康园生态农业',
      desc: '高性价比产品',
      path: '/pages/index/index?shareUserId=' + shareUserId
    }
  },

  onPullDownRefresh() {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.getIndexData();
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },

  getIndexData: function () {
    let that = this;
    util.request(api.IndexUrl).then(function (res) {
      if (res.errno === 0) {
        if (res.data.grouponList != undefined) {
          that.setData({
            groupons: res.data.grouponList
          });
        }
        if (res.data.noStockGoodsList != undefined) {
          that.setData({
            noStockGoods: res.data.noStockGoodsList
          });
        }
        if (res.data.seckillGoodsList != undefined) {
          that.setData({
            hotGoods: res.data.seckillGoodsList
          });
        }
   
        that.setData({
          newGoods: res.data.newGoodsList,
          banner: res.data.banner,
          channel: res.data.channel,
          coupon: res.data.couponList
        });
      }
    });
    //商品的数量
    util.request(api.GoodsCount).then(function (res) {
      that.setData({
        goodsCount: res.data.goodsCount
      });
    });

    this.getGoodsCountMoney();
  },

  //购物车中选中的商品的数量和金额
  getGoodsCountMoney: function () {
    let that = this;
    util.request(api.GoodsCountMoney).then(function (res) {
      if (res.errno == 0) {
        that.setData({
          number: res.data.number,
          money: res.data.money
        });
      }
    });
  },

  // 加入购物车
  addCard: function (event) {
    let that = this;
    if (!app.globalData.hasLogin) {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    }

    //添加到购物车
    util.request(api.CartAdd, {
        goodsId: event.currentTarget.id,
        number: 1
      }, "POST")
      .then(function (res) {
        let _res = res;
        if (_res.errno == 0) {
          that.setData({
            number: res.data.number,
            money: res.data.money
          });
        } else {
          wx.showToast({
            image: '/static/images/icon_error.png',
            title: _res.errmsg,
            mask: true
          });
        }
      });
  },

  checkoutOrder: function () {
    //获取已选择的商品
    let that = this;
    // storage中设置了cartId，则是购物车购买
    try {
      //购物车ID
      wx.setStorageSync('cartId', 0);
      //优惠券
      wx.setStorageSync('couponId', 0);
      //非团购为0
      wx.setStorageSync('grouponRulesId', 0);
      //该组团购标识，非团购-1
      wx.setStorageSync('grouponId', -1);
      wx.navigateTo({
        url: '/pages/checkout/checkout'
      })
    } catch (e) {}
  },

  //立即购买
  addFast: function (e) {
    var that = this;
    //立即购买
    util.request(api.CartFastAdd, {
        goodsId: e.currentTarget.dataset.id,
        number: 1
      }, "POST")
      .then(function (res) {
        if (res.errno == 0) {
          try {
            wx.setStorageSync('cartId', res.data);
            wx.setStorageSync('grouponRulesId', 0);
            wx.setStorageSync('grouponId', -1);
            wx.navigateTo({
              url: '/pages/checkout/checkout'
            })
          } catch (e) {}
        } else {
          wx.showToast({
            image: '/static/images/icon_error.png',
            title: res.errmsg,
            mask: true
          });
        }
      });
  },

  onLoad: function (options) {
    this.setData({
      colseCoupon: false
    });
    //如果有分享用户，则设置
    if (options.shareUserId) {
      wx.setStorageSync('shareUserId', options.shareUserId);
    }

    // 页面初始化 options为页面跳转所带来的参数
    if (options.scene) {
      //这个scene的值存在则证明首页的开启来源于朋友圈分享的图,同时可以通过获取到的goodId的值跳转导航到对应的详情页
      var scene = decodeURIComponent(options.scene);
      console.log("scene:" + scene);

      let info_arr = [];
      info_arr = scene.split(',');
      let _type = info_arr[0];
      let id = info_arr[1];

      if (_type == 'goods') {
        wx.navigateTo({
          url: '../goods/goods?id=' + id
        });
      } else if (_type == 'groupon') {
        wx.navigateTo({
          url: '../goods/goods?grouponId=' + id
        });
      } else {
        if (id != null) {
          wx.setStorageSync('shareUserId', id);
        }
        wx.navigateTo({
          url: '../index/index'
        });
      }
    }

    // 页面初始化 options为页面跳转所带来的参数
    if (options.grouponId) {
      //这个pageId的值存在则证明首页的开启来源于用户点击来首页,同时可以通过获取到的pageId的值跳转导航到对应的详情页
      wx.navigateTo({
        url: '../goods/goods?grouponId=' + options.grouponId
      });
    }

    // 页面初始化 options为页面跳转所带来的参数
    if (options.goodId) {
      //这个goodId的值存在则证明首页的开启来源于分享,同时可以通过获取到的goodId的值跳转导航到对应的详情页
      wx.navigateTo({
        url: '../goods/goods?id=' + options.goodId
      });
    }

    // 页面初始化 options为页面跳转所带来的参数
    if (options.orderId) {
      //这个orderId的值存在则证明首页的开启来源于订单模版通知,同时可以通过获取到的pageId的值跳转导航到对应的详情页
      wx.navigateTo({
        url: '../ucenter/orderDetail/orderDetail?id=' + options.orderId
      });
    }
    this.getIndexData();
  },
  onReady: function () {
    // 页面渲染完成
    let that = this;
    let userInfo = wx.getStorageSync('userInfo');
    if (!that.data.colseCoupon && userInfo && that.data.coupon.length > 0) {
      that.setData({
        window: true
      });
    }
  },
  onShow: function () {
    // 每个机型的尺寸不一致  
    // 在app.js中获取到的 statusBarHeight 用于控制头部的高度
    this.setData({
      //height: app.globalData.height,
    });
    // 每次页面显示，需获取是否用户登录，如果用户登录，则查询用户是否有优惠券，有则弹出优惠券领取窗口
    let that = this;
    let userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      util.request(api.GetUserCoupon, null, 'GET').then(res => {
        if (res.errno === 0) {
          that.setData({
            coupon: res.data.couponList
          });

          if (!that.data.colseCoupon && userInfo && that.data.coupon.length > 0) {
            that.setData({
              window: true
            });
          } else {
            that.setData({
              window: false
            });
          }
        }
      })
      //购物车中选中的商品的数量和金额
      this.getGoodsCountMoney();
    }
  },
  search: function (e) {
    wx.navigateTo({
      url: '/pages/search/search'
    });
  },
  onHide: function () {},
  onUnload: function () {},
  onColse: function () {
    this.setData({
      window: false,
      colseCoupon: true
    });
  },
  getCoupon(e) {
    if (!app.globalData.hasLogin) {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    }

    let couponId = e.currentTarget.dataset.index
    util.request(api.CouponReceive, {
      couponId: couponId
    }, 'POST').then(res => {
      if (res.errno === 0) {
        wx.showToast({
          title: "恭喜领券成功"
        })
      } else {
        util.showErrorToast(res.errmsg);
      }
    })
  },
  //进入活动区
  goActive: function (e) {
    let link = e.currentTarget.dataset.link;
    if (link) {
      wx.navigateTo({
        url: "/pages/activeGoods/activeGoods"
      });
    }
  },
})